import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { ConnectedRouter, routerReducer, push } from 'react-router-redux'
import { persistState } from 'redux-devtools';

import middlewares from './middlewares'

import reducers from '../reducer';
import DevTools from '../../containers/DevTools';

const enhancer = compose(
  applyMiddleware(...middlewares),
  // 启用带有monitors（监视显示）的DevTools
  DevTools.instrument(),
  persistState(getDebugSessionKey())
);

function getDebugSessionKey() {
  // You can write custom logic here!
  // By default we try to read the key from ?debug_session=<key> in the address bar
  const matches = window.location.href.match(/[?&]debug_session=([^&#]+)\b/);
  return (matches && matches.length > 0)? matches[1] : null;
}

export default function configureStore(initialState) {
  const store = createStore(
    combineReducers({
      reducers,
      router: routerReducer
    }),
    enhancer
  )
  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducer', () => {
      const nextRootReducer = require('../reducer/index').default;
      store.replaceReducer(nextRootReducer);
    });
  }
  return store;
}

